// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    userRole: '', // 用户角色
    loading: false,
    showRoleSelect: true, // 显示角色选择界面
    // 学生数据
    courses: [],
    unpaidItems: [],
    // 老师数据
    students: [],
    // 统计数据
    totalUnpaidAmount: 0,
    unpaidStudentCount: 0
  },

  onLoad() {
    // 检查缓存中是否有用户角色
    const cachedRole = wx.getStorageSync('userRole');

    if (cachedRole) {
      // 如果有缓存的角色，直接使用
      this.setData({
        userRole: cachedRole,
        showRoleSelect: false,
        loading: true
      });

      // 根据角色加载数据
      setTimeout(() => {
        if (cachedRole === 'student') {
          this.loadStudentData();
        } else if (cachedRole === 'teacher') {
          this.loadTeacherData();
        }

        this.setData({
          loading: false
        });
      }, 500);
    } else {
      // 没有缓存角色，显示角色选择界面
      this.setData({
        showRoleSelect: true,
        userRole: '',
        loading: false
      });
    }
  },

  onShow() {
    // 只有当没有角色时才显示角色选择界面
    if (!this.data.userRole) {
      const cachedRole = wx.getStorageSync('userRole');
      if (!cachedRole) {
        this.setData({
          showRoleSelect: true,
          userRole: '',
          loading: false
        });
      }
    }
  },

  // 选择角色
  selectRole(e) {
    const role = e.currentTarget.dataset.role;

    // 显示选择反馈
    wx.showToast({
      title: role === 'student' ? '已选择学生身份' : '已选择老师身份',
      icon: 'success',
      duration: 1000
    });

    // 保存角色到缓存
    wx.setStorageSync('userRole', role);

    // 更新角色并隐藏角色选择界面
    this.setData({
      userRole: role,
      showRoleSelect: false,
      loading: true
    });

    // 根据角色加载数据
    setTimeout(() => {
      if (role === 'student') {
        this.loadStudentData();
      } else if (role === 'teacher') {
        this.loadTeacherData();
      }

      this.setData({
        loading: false
      });
    }, 1000);
  },

  // 切换角色（添加新方法，用于手动切换角色）
  switchRole() {
    // 清除缓存的角色
    wx.removeStorageSync('userRole');

    // 重置界面状态
    this.setData({
      userRole: '',
      showRoleSelect: true,
      loading: false,
      // 清空数据
      courses: [],
      unpaidItems: [],
      students: [],
      totalUnpaidAmount: 0,
      unpaidStudentCount: 0
    });
  },

  // 加载学生数据
  loadStudentData() {
    // 加载课程数据
    const courses = [
      {
        id: 1,
        title: '数据结构与算法',
        teacher: '李教授',
        duration: '40小时',
        progress: 75,
        totalVideos: 20,
        watchedVideos: 15,
        status: 'learning'
      },
      {
        id: 2,
        title: 'Web前端开发',
        teacher: '王老师',
        duration: '35小时',
        progress: 30,
        totalVideos: 18,
        watchedVideos: 5,
        status: 'learning'
      },
      {
        id: 3,
        title: '数据库原理',
        teacher: '张教授',
        duration: '30小时',
        progress: 100,
        totalVideos: 15,
        watchedVideos: 15,
        status: 'completed'
      }
    ];

    // 加载未缴费项目
    const unpaidItems = [
      {
        id: 1,
        title: '2024年春季学期学费',
        amount: 3690,
        dueDate: '2024-02-28',
        type: 'tuition',
        status: 'unpaid'
      },
      {
        id: 2,
        title: '教材费',
        amount: 380,
        dueDate: '2024-03-15',
        type: 'materials',
        status: 'unpaid'
      }
    ];

    const totalUnpaidAmount = unpaidItems.reduce((sum, item) => sum + item.amount, 0);

    this.setData({
      courses: courses,
      unpaidItems: unpaidItems,
      totalUnpaidAmount: totalUnpaidAmount
    });
  },

  // 加载老师数据
  loadTeacherData() {
    const students = [
      {
        id: 1,
        name: '张三',
        studentId: '2023001',
        class: '计算机科学与技术1班',
        avatar: '/images/avatar1.png',
        paymentStatus: 'paid',
        totalAmount: 7380.00,
        paidAmount: 7380.00,
        unpaidAmount: 0,
        courseProgress: {
          total: 4,
          completed: 1,
          learning: 2,
          notStarted: 1
        },
        lastLoginTime: '2024-01-15 14:30'
      },
      {
        id: 2,
        name: '李四',
        studentId: '2023002',
        class: '计算机科学与技术1班',
        avatar: '/images/avatar2.png',
        paymentStatus: 'partial',
        totalAmount: 7380.00,
        paidAmount: 5800.00,
        unpaidAmount: 1580.00,
        courseProgress: {
          total: 4,
          completed: 0,
          learning: 2,
          notStarted: 2
        },
        lastLoginTime: '2024-01-14 09:15'
      },
      {
        id: 3,
        name: '王五',
        studentId: '2023003',
        class: '计算机科学与技术2班',
        avatar: '/images/avatar3.png',
        paymentStatus: 'unpaid',
        totalAmount: 7380.00,
        paidAmount: 0,
        unpaidAmount: 7380.00,
        courseProgress: {
          total: 4,
          completed: 0,
          learning: 0,
          notStarted: 4
        },
        lastLoginTime: '2024-01-10 16:45'
      },
      {
        id: 4,
        name: '赵六',
        studentId: '2023004',
        class: '计算机科学与技术2班',
        avatar: '/images/avatar4.png',
        paymentStatus: 'paid',
        totalAmount: 7380.00,
        paidAmount: 7380.00,
        unpaidAmount: 0,
        courseProgress: {
          total: 4,
          completed: 2,
          learning: 1,
          notStarted: 1
        },
        lastLoginTime: '2024-01-15 11:20'
      }
    ];

    const unpaidStudentCount = students.filter(s => s.paymentStatus !== 'paid').length;

    this.setData({
      students: students,
      unpaidStudentCount: unpaidStudentCount
    });
  },

  // 学生功能：进入课程
  enterCourse(e) {
    const courseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/student/video-player/video-player?courseId=${courseId}`
    });
  },

  // 学生功能：查看所有课程
  viewAllCourses() {
    wx.navigateTo({
      url: '/pages/student/courses/courses'
    });
  },

  // 学生功能：去缴费
  goPayment(e) {
    const itemId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/student/payment/payment?itemId=${itemId}`
    });
  },

  // 学生功能：查看缴费记录
  viewPaymentRecords() {
    wx.navigateTo({
      url: '/pages/student/payment/payment?tab=1'
    });
  },

  // 老师功能：查看学生详情
  viewStudentDetail(e) {
    const studentId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/teacher/student-detail/student-detail?studentId=${studentId}`
    });
  },

  // 老师功能：查看所有学生
  viewAllStudents() {
    wx.navigateTo({
      url: '/pages/teacher/student-list/student-list'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.checkUserRoleAndLoadData();
    wx.stopPullDownRefresh();
  },

  // 分享功能
  onShareAppMessage(res) {
    return {
      title: '教务小程序（原型）',
      path: '/pages/index/index',
    };
  },

  // 分享到朋友圈（小程序基础库 2.11.3 开始支持）
  onShareTimeline() {

    return {
      title: '教务小程序（原型）',
      imageUrl: '/images/share-default.png' // 可选的分享图片
    };
  }

});
